$(document).ready(function () {
    var addScheduleValidate = $("#AddSchedule").validate({
        debug: false,
        focusInvalid: false,
        onkeyup: false,
        groups: {
            group1: "CrewName",
            group2: "ids"
        },
        errorPlacement: function (error, element) {
            if (element.attr("name") == "CrewName") {
                error.appendTo(element.parent().parent());
            } else if (element.attr("name") == "ids") {
                $("#errorMsg").replaceWith(error);
            } else {
                error.appendTo(element.parent());
            }
        },
        submitHandler: function (form) {
            var data = $(form).serialize();
            $.ajax({
                url: "AddSchedule",
                method: "POST",
                async: true,
                dataType: "json",
                data: data,
                timeout: timeout,
                success: function (F) {
                    alert(F.Message);
                    if (F.Result) {
                        select("list");
                        query("keep=true", "QuerySchedule");
                    }
                }
            }).fail(function (F, G) {
                alert("浏览器超时未响应，请刷新重试");
            });
            return false;
        },

        rules: {
            Start: {
                required: true
            },
            CrewName: {
                required: true
            },
            Shift: {
                required: true
            },
            PaymentId: {
                required: true
            },
            Ratio: {
                required: true
            },
            ids: {
                required: true
            }
        },
        messages: {
            Start: {
                required: "服务时间不能为空"
            },
            CrewName: {
                required: "服务人员不能为空"
            },
            Shift: {
                required: "班次不能为空"
            },
            PaymentId: {
                required: "结算标准不能为空"
            },
            Ratio: {
                required: "分成比例不能为空"
            },
            ids: {
                required: "服务订单必须选择"
            }
        }

    });

    var editFormValidate = $("#editForm").validate({
        debug: false,
        focusInvalid: false,
        onkeyup: false,
        submitHandler: function (form) {
            var jsonData = $("div#edit form").serializeForm();
            $.ajax({
                url: "EditSchedule",
                method: "POST",
                contentType: "application/json;charset=UTF-8",
                async: true,
                dataType: "json",
                data: JSON.stringify(jsonData),
                timeout: timeout,
                success: function (rep) {
                    alert(rep.Message);
                    select("list");
                }
            }).fail(function (T, S) {
                alert("浏览器超时未响应，请刷新重试");
            });
            return false;
        },

        rules: {
            CrewName: {
                required: true
            },
            Start: {
                required: true
            },
            Shift: {
                required: true
            },
            PaymentId: {
                required: true
            },
            Ratio: {
                required: true
            },
            Pay: {
                required: true
            }
        },
        messages: {
            CrewName: {
                required: "服务人员不能为空"
            },
            Start: {
                required: "服务时间不能为空"
            },
            Shift: {
                required: "班次不能为空"
            },
            PaymentId: {
                required: "结算标准不能为空"
            },
            Ratio: {
                required: "分成比例不能为空"
            },
            Pay: {
                required: "结算金额不能为空"
            }
        }

    });

    function D(N) {
        var O = $("div#list table.list tbody");
        O.empty();
        O.append('<tr><td colspan="20">数据加载中...</td></tr>');
        $.ajax({
            url: "SchedulePage",
            dataType: "json",
            data: "page=" + N,
            timeout: timeout,
            success: function (P) {
                update(P);
            }
        }).fail(function (Q, P) {
            alert("浏览器超时未响应，请刷新重试");
        });
    }
    var E = {
        count: 1,
        start: 1,
        display: 20,
        border: true,
        border_color: "#DDD",
        text_color: "#3399D5",
        background_color: "#FFF",
        border_hover_color: "#DDD",
        text_hover_color: "#737373",
        background_hover_color: "#F5F5F5",
        images: false,
        mouse: "press",
        onChange: D
    };
    $("div#lpager").paginate(E);
    window.update = function (Q) {
        var N = $("div#list table.list tbody");
        var V = Q.Items;
        $("div#list table.list input.selall").prop("checked", false);
        N.empty();
        var O = Q.Page * 10 - 9;
        var R = "</td><td>";
        if (V.length > 0) {
            for (var S = 0; S < V.length; S++) {
                var P = V[S];
                var U = P.Adjust || "";
                var T = P.Rate || "";
                var W = P.Note || "";
                N.append('<tr><td><input name="ids" class="row" type="checkbox" value="' + P.Id + '"/></td><td>' + (P.Area + "/" + P.Bed) + R + P.CustomerName + R + P.ServiceType + R + P.ServiceName + R + P.CrewName + R + $.toSpace(P.Start) + R + $.toSpace(P.End) + R + P.ShiftName + R + P.ServicePrice + R + P.Ratio + R + P.Pay + R + U + '</td><td><button data-id="' + P.Id + '" class="edit btn btn-warning"> <i class="fa fa-edit fa-lg"></i> 重排</button></tr>');
            }
        } else {
            N.append('<tr><td colspan="20">没有相关记录信息</td></tr>');
        }
        E.start = Q.Page;
        E.count = Q.Total;
        $("div#lpager").paginate(E);
    };
    $("div#list div.query button.query").click(function (N) {
        query($("div#list div.query form").serialize(), "QuerySchedule");
        return false;
    });
    query($("div#list div.query form").serialize(), "QuerySchedule");
    $("div#list ul.tool button.delete").click(function (N) {
        if (confirm("您确定要删除所有选中的记录吗？")) {
            var O = $("div#list table.list tbody input.row:checked").serialize();
            $.ajax({
                url: "DeleteSchedules",
                dataType: "json",
                data: O,
                timeout: timeout,
                success: function (P) {
                    alert(P.Message);
                    if (P.Result) {
                        query("keep=true", "QuerySchedule");
                    }
                }
            }).fail(function (Q, P) {
                alert("浏览器超时未响应，请刷新重试");
            });
        }
    });
    var J;
    $("div#add input.End").change(function () {
        loadOrder($("div#add form").serialize(), "QueryAvailableOrders");
    });

    $("div#add input.Start").change(function () {
        var Q = $("div#add input.Start").val();
        var R = new Date(Q.replace(/-/g, "/"));
        var O = parseFloat($("div#add select.Shift").val());
        var N = O ? 12 : 24;
        var P = new Date(R.getTime() + 3600 * 1000 * N);
        $("div#add input.End").val(P.format("yyyy-mm-dd HH:MM")).change();
    });
    $("div#add select.Shift").change(function () {
        var Q = new Date($("div#add input.Start").val().replace(/-/g, "/"));
        var O = parseFloat($("div#add select.Shift").val());
        var N = O == 2 ? 20 : 8;
        Q.setHours(N);
        var N = O ? 12 : 24;
        var P = new Date(Q.getTime());
        P.setHours(P.getHours() + N);
        $("div#add input.Start").val(Q.format("yyyy-mm-dd HH:MM"));
        $("div#add input.End").val(P.format("yyyy-mm-dd HH:MM")).change();
    });

    function renderOrder(Q) {
        var N = $("div#add table.order tbody");
        N.empty();
        $("div#add table.list input.selall").prop("checked", false);
        for (var R = 0; R < Q.length; R++) {
            var O = Q[R];
            var P = O.Area + "/" + O.Bed;
            var T = O.Adjust || "";
            var S = O.Rate || "";
            var U = O.Note || "";
            N.append('<tr><td><input name="ids" class="row" type="checkbox" value="' + O.Id + '"/></td><td>' + P + "</td><td>" + O.CustomerName + "</td><td>" + O.Category + "</td><td>" + O.ServiceName + "</td><td>" + $.toSpace(O.Start) + "</td><td>" + $.toSpace(O.End) + "</td></tr>");
        }

        $("div#add table.order").makeTableFilter(",0,");
    }
    /*
    *加载可以排班的订单
    */
    function loadOrder(data, url) {
        var P = $("div#add table.order tbody");
        P.empty();
        P.append('<tr><td colspan="20">数据加载中...</td></tr>');
        $.ajax({
            url: url,
            dataType: "json",
            data: data,
            timeout: timeout,
            success: function (Q) {
                renderOrder(Q);
            },
            error: function (R, Q, S) {
                alert("浏览器超时未响应，请刷新重试");
            }
        });
    }
    function renderSchedule(data) {
        var N = $("div#add table.schedule tbody");
        N.empty();
        for (var R = 0; R < data.length; R++) {
            var O = data[R];
            var P = O.Area + "/" + O.Bed;
            var T = O.Adjust || "";
            var S = O.Rate || "";
            var U = O.Note || "";
            N.append('<tr><td>' + P + "</td><td>" + O.CustomerName + "</td><td>" + O.ShiftName + "</td><td>" + $.toSpace(O.Start) + "</td><td>" + $.toSpace(O.End) + "</td></tr>");
        }
    }
    function loadSchedule(data, url) {
        var P = $("div#add table.schedule tbody");
        P.empty();
        P.append('<tr><td colspan="20">数据加载中...</td></tr>');
        $.ajax({
            url: url,
            dataType: "json",
            data: data,
            timeout: timeout,
            success: function (Q) {
                renderSchedule(Q);
            },
            error: function (R, Q, S) {
                alert("浏览器超时未响应，请刷新重试");
            }
        });
    }
    $("div#list ul.tool button.add").click(function (N) {
        $("div#add input.Start").val("");
        $("div#add input.End").val("");
        $("div#add input.CrewId").val("");
        $("div#add input.CrewName").val("");
        $("div#add input.IsHoliday").prop("checked", false);
        $("div#add select.PaymentId").change();
        $("div#add select option.default").prop("selected", "selected");
        $("div#add table.list tbody").empty();
        select("add");
        return false;
    });
    /*
    *加载排班信息赋值
    */
    function refreshSchedule(N) {
        $("div#add input.CrewId").val(N.Id);
        $("div#add input.CrewName").val(N.Name);
        $("div#add input.CrewTel").val(N.Tel);
        $("div#add select.PaymentId").val(N.PaymentId);
        $("div#add input.Ratio").val(N.Ratio);
        //加载排班信息
        loadSchedule($("div#add form").serialize(), "QueryAvailableSchedules");
    }
    $("div#add button.browser").click(function (N) {
        $("div#crew").dialog("open");
        $("div#wpager").paginate(C);
        L($("div#crew div.query form").serialize(), "QueryCrew");
        return false;
    });
    //pay样式控件值改变,计算结算金额
    $("div#edit .pay").change(function (O) {
        //收费标准
        var servicePrice = parseFloat($("div#edit input.ServicePrice").val());
        //班次
        var shift = parseFloat($("div#edit select.Shift").val());
        //分成比例
        var ratio = parseFloat($("div#edit input.Ratio").val());
        //节假日双倍
        var isHoliday = $("div#edit input.IsHoliday").prop("checked") ? 2 : 1;
        //调整金额
        var adjust = parseFloat($("div#edit input.Adjust").val()) || 0;
        var shiftRate = shift == "0" ? 1 : 0.5;
        if (!isNaN(servicePrice) && !isNaN(ratio)) {
            $("div#edit input.Pay").val(servicePrice * ratio * isHoliday * shiftRate + adjust);
        }
    });
    //开始时间
    $("div#edit input.Start").change(function () {
        var Q = new Date($("div#edit input.Start").val().replace(/-/g, "/"));
        var O = parseFloat($("div#edit select.Shift").val());
        var N = O ? 12 : 24;
        var P = new Date(Q.getTime() + 3600 * 1000 * N);
        $("div#edit input.End").val(P.format("yyyy-mm-dd HH:MM"));
    });
    //班次
    $("div#edit select.Shift").change(function () {
        var Q = new Date($("div#edit input.Start").val().replace(/-/g, "/"));
        var O = parseFloat($("div#edit select.Shift").val());
        var N = O == 2 ? 20 : 8;
        Q.setHours(N);
        var N = O ? 12 : 24;
        var P = new Date(Q.getTime());
        P.setHours(P.getHours() + N);
        $("div#edit input.Start").val(Q.format("yyyy-mm-dd HH:MM"));
        $("div#edit input.End").val(P.format("yyyy-mm-dd HH:MM"));
    });

    $("div.view select.PaymentId").change(function (O) {
        var N = $(this).find("option:selected");
        $(this).parents("div.view").find("input.Ratio").val(N.data("ratio")).change();
    });

    function M(N) {
        $("div#edit input").val("");
        $("div#edit select option.default").prop("selected", "selected");
        if (N) {
            $("div#edit input.Id").val(N.Id);
            $("div#edit input.OrderId").val(N.OrderId);
            $("div#edit input.CustomerName").val(N.CustomerName);
            $("div#edit input.ServiceName").val(N.ServiceName);
            $("div#edit input.ServicePrice").val(N.ServicePrice);
            $("div#edit input.CrewId").val(N.CrewId);
            $("div#edit input.CrewName").val(N.CrewName);
            $("div#edit input.CrewTel").val(N.CrewTel);
            $("div#edit input.Start").val($.toSpace(N.Start));
            $("div#edit input.End").val($.toSpace(N.End));
            $("div#edit select.Shift").val(N.Shift);
            $("div#edit select.Shift").val(N.Shift);
            $("div#edit input.IsHoliday").prop("checked", N.IsHoliday);
            $("div#edit select.PaymentId").val(N.PaymentId);
            $("div#edit input.Ratio").val(N.Ratio);
            $("div#edit input.Adjust").val(N.Adjust);
            $("div#edit input.Pay").val(N.Pay);
            $("div#edit input.Rate").val(N.Rate);
            $("div#edit input.Note").val(N.Note);
        }
    }

    $("button.cancel").click(function (N) {
        addScheduleValidate.resetForm();
        editFormValidate.resetForm();
        select("list");
        return false;
    });
    $("div#list table.list tbody").click(function (N) {
        var O = $(N.target);
        if (O.is("button.edit")) {
            var P = O.data("id");
            $.ajax({
                url: "GetSchedule",
                dataType: "json",
                data: "Id=" + P,
                timeout: timeout,
                success: function (Q) {
                    M(Q);
                    select("edit");
                }
            }).fail(function (R, Q) {
                alert("浏览器超时未响应，请刷新重试");
            });
        }
    });

    function K(N) {
        $("div#edit input.CrewId").val(N.Id);
        $("div#edit input.CrewName").val(N.Name);
        $("div#edit input.CrewTel").val(N.Tel);
        $("div#edit input.Ratio").val(N.Ratio);
        if (N.Ratio) {
            $("div#edit input.Pay").val(N.Ratio * $("div#edit input.ServicePrice").val());
        }
    }
    $("div#edit button.browser").click(function (N) {
        J = K;
        $("div#crew").dialog("open");
        $("div#wpager").paginate(C);
        L($("div#crew div.query form").serialize(), "QueryCrew");
        return false;
    });
    var C = {
        count: 1,
        start: 1,
        display: 20,
        border: true,
        border_color: "#DDD",
        text_color: "#3399D5",
        background_color: "#FFF",
        border_hover_color: "#DDD",
        text_hover_color: "#737373",
        background_hover_color: "#F5F5F5",
        images: false,
        mouse: "press",
        onChange: H
    };

    function I(P) {
        var N = $("div#crew table.list tbody");
        var T = P.Items;
        N.empty();
        if (T.length > 0) {
            for (var Q = 0; Q < T.length; Q++) {
                var O = T[Q];
                var U = O.Skill || "";
                var S = O.IdNo || "";
                var R = O.Tel || "";
                N.append("<tr><td>" + O.Name + "</td><td>" + O.Gender + "</td><td>" + S + "</td><td>" + O.Type + "</td><td>" + U + "</td><td>" + O.Status + "</td><td>" + R + "</td><td>" + O.OwnerUnitName + "</td><td>" + O.ServiceUnitName + '</td><td><button data-id="' + O.Id + '" class="select btn btn-success"><i class="fa fa-check fa-lg"></i> 选 择</button></td></tr>');
            }
        } else {
            N.append('<tr><td colspan="20">没有相关记录信息</td></tr>');
        }
        C.start = P.Page;
        C.count = P.Total;
        $("div#wpager").paginate(C);
    }
    function H(N) {
        var O = $("div#crew table.list tbody");
        O.empty();
        O.append('<tr><td colspan="20">数据加载中...</td></tr>');
        $.ajax({
            url: "CrewPage",
            dataType: "json",
            data: "page=" + N,
            timeout: timeout,
            success: function (P) {
                I(P);
            }
        }).fail(function (Q, P) {
            alert("浏览器超时未响应，请刷新重试");
        });
    }
    function L(O, N) {
        var P = $("div#crew table.list tbody");
        P.empty();
        P.append('<tr><td colspan="20">数据加载中...</td></tr>');
        $.ajax({
            url: N,
            dataType: "json",
            data: O,
            timeout: timeout,
            success: function (Q) {
                I(Q);
            },
            error: function (R, Q, S) {
                alert("浏览器超时未响应，请刷新重试");
            }
        });
    }
    $("div#crew div.query button.query").click(function (N) {
        L($("div#crew div.query form").serialize(), "QueryCrew");
        return false;
    });
    $("div#crew table.list tbody").click(function (N) {
        var O = $(N.target);
        if (O.is("button.select")) {
            var P = O.data("id");
            $.ajax({
                url: "GetCrew",
                dataType: "json",
                data: "Id=" + P,
                timeout: timeout,
                success: function (Q) {
                    //刷新排班
                    refreshSchedule(Q);
                    //刷新订单
                    loadOrder($("div#add form").serialize(), "QueryAvailableOrders");
                    $("div#crew").dialog("close");
                }
            }).fail(function (R, Q) {
                alert("浏览器超时未响应，请刷新重试");
            });
        }
    });
});